// 图片加载缓存管理

const cache = [];
const CACHE_IMG_NUM = 300;

/**
 * 解析图片链接中的尺寸
 * @param url
 * @return {{size: number, src: (string|string)}}
 */
const parseImageUrl = (url = '') => {
    const [, src, size] = url.match(/(.+)\/w\/(\d+)$/i) || [url, url, '0'];
    return {
        src,
        size: +size,
    };
};

/**
 * 将尺寸信息拼接成完整的url
 * @param src
 * @param size
 * @return {string}
 */
const transImageUrl = ({ src, size }) => `${src}/w/${size}`.replace(/\/w\/0$/, '');

/**
 * 判断图片是否已经加载
 * @export
 * @param {string} [url='']
 * @returns
 */
const has = (url = '') => {
    const { src, size } = parseImageUrl(url);
    const match = cache.find((item) => item.src === src && (item.size === 0 || item.size >= size));
    return match && transImageUrl(match);
};

/**
 *添加缓存
 * @export
 * @param {string} [url='']
 */
const add = (url = '') => {
    if (cache.length >= CACHE_IMG_NUM) {
        cache.shift();
    }
    if (!has(url)) {
        const item = parseImageUrl(url);
        // 删除小尺寸
        const index = cache.findIndex((exist) => exist.src === item.src);
        index >= 0 && cache.splice(index, 1);
        cache.push(item);
    }
};

/**
 * 加载图片
 * @export
 * @param {string} [src='']
 * @param {function} callback
 * @param {number} [timeout=5000]
 * @returns
 */
function load(src = '', callback, timeout = 5000) {
    let loadTimeout;
    let isExec = false;
    // 成功回调只执行一次
    const handleLoad = (event) => {
        if (isExec) return;
        isExec = true;
        add(src);
        clearTimeout(loadTimeout);
        callback(event || {});
    };

    const existUrl = has(src);

    if (existUrl) {
        handleLoad({
            fromCache: true,
            existUrl,
        });
        return;
    }

    const image = document.createElement('img');
    image.addEventListener('load', handleLoad);
    image.addEventListener('abort', handleLoad);
    image.addEventListener('error', handleLoad);
    image.src = src;

    loadTimeout = setTimeout(handleLoad, timeout); // 5s后强制显示

    if (image.src === window.location.href) {
        console.error('LazyImage组件src有误，请检查传值是否为空。');
    }
}

export default {
    load,
    has,
    add,
};
